package org.jianfa.mq.seckill.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.jianfa.mq.seckill.filter.AjaxLoginAuthorizationFilter;
import org.jianfa.mq.seckill.filter.AjaxLogoutAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class ShiroConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/seckill/login", "ajaxLogin");
        chainDefinition.addPathDefinition("/seckill/logout", "ajaxLogout");
        chainDefinition.addPathDefinition("/seckill/**", "ajaxLogin");
        return chainDefinition;
    }

    @Bean
    public Realm realm() {
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        return jdbcRealm;
    }

    @Bean
    public FilterRegistrationBean ajaxLoginRegister(AjaxLoginAuthorizationFilter ajaxLoginAuthorizationFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean(ajaxLoginAuthorizationFilter);
        registration.setEnabled(false);
        return registration;
    }

    @Bean("ajaxLogin")
    public AjaxLoginAuthorizationFilter ajaxLoginAuthorizationFilter() {
        return new AjaxLoginAuthorizationFilter();
    }

    @Bean
    public FilterRegistrationBean ajaxLogoutRegister(AjaxLogoutAuthorizationFilter ajaxLogoutAuthorizationFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean(ajaxLogoutAuthorizationFilter);
        registration.setEnabled(false);
        return registration;
    }

    @Bean("ajaxLogout")
    public AjaxLogoutAuthorizationFilter ajaxLogoutAuthorizationFilter() {
        return new AjaxLogoutAuthorizationFilter();
    }
}
